<template>
  <el-upload
    class="avatar-uploader"
    :http-request="fnUploadRequestFiles"
    :on-success="uploadSuccessFiles"
    :before-upload="beforeFileUpload"
    action=""
    :show-file-list="false"
  >
    <img v-if="src" :src="src" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>
<script>
import oss from '@/utils/aliyunOssCommon'
export default {
  name: 'AvatarUpload',
  props: {
    tip: {
      type: String,
      default: '上传文件小于 50M,word、pdf、wps、Excel'
    },
    size: {
      type: Number,
      default: 50
    },
    src: {
      type: String,
      default: ''
    },
    path: {
      type: String,
      default: 'upload/'
    }
  },
  methods: {
    // 附件提交到服务器
    async fnUploadRequestFiles(option) {
      oss.ossUploadFile(option, this.path, option.file.uid + this.getType(option.file.name))
    },
    // 文件上传之前
    beforeFileUpload(file) {
      const isLt50M = file.size / 1024 < 1024 * this.size
      if (!isLt50M) {
        this.$message.error('文件大小' + this.size + 'MB以下')
        return false
      }
      return true
    },
    // 文件上传成功
    uploadSuccessFiles(response, file, fileList) {
      for (let i = 0; i < fileList.length; i++) {
        if (fileList[i].response !== undefined) {
          this.$emit('imageUrl', 'https://oneraku-resource.oss-cn-shanghai.aliyuncs.com/' + fileList[i].response.name)
        }
      }
    },
    getType(file) {
      var filename = file
      var index1 = filename.lastIndexOf('.')
      var index2 = filename.length
      var type = filename.substring(index1, index2)
      return type
    }
  }
}
</script>
<style scoped>
    .avatar-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      width: 100px;
      height: 100px;
    }
    .avatar-uploader:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
    }
    .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }
</style>
